<?php

header("Content-type: image/png");

include('includes/connection_settings.php');

//Strips " and ' marks
$bannedMarks = array("\"", "'");

$_COOKIE['username'] = str_replace($bannedMarks, "", $_COOKIE['username']);


$table = mysql_query("SELECT dictionary FROM choices WHERE {$_COOKIE['username']} = true");

//If no dictionaries selected
if (mysql_result($table, 0, 0) == "") {
 $image=imagecreate(200,20);

 $headerBox = imagecolorallocate($image, 138, 97, 50);
 $black = imagecolorallocate($image, 0, 0, 0);
 imagestring($image,2, 3, 3, "No dictionaries choosen", $black);

 imagepng($image);

 imagedestroy($image);

 mysql_close($connection);
 exit;
}

for ($i = 0;$i <= mysql_num_rows($table); $i++) {
 $dictionariesInArray[$i] = mysql_result($table, $i, 0);
}

$command = "SELECT SUM(points_{$_COOKIE['username']}) FROM words WHERE";
for ($i = 0; $i < count($dictionariesInArray) - 1; $i++) {
 if ($i == 0) {
  $command = $command . " dictionary = '{$dictionariesInArray[$i]}'";
 }
 else {
  $command = $command . " OR dictionary = '{$dictionariesInArray[$i]}'";
 }
}

$table = mysql_query($command);
$summedPoints = mysql_result($table, 0, 0);

//Counts how many lines (word pairs)
$command = "SELECT points_{$_COOKIE['username']} FROM words WHERE";
for ($i = 0; $i < count($dictionariesInArray) - 1; $i++) {
 if ($i == 0) {
  $command = $command . " dictionary = '{$dictionariesInArray[$i]}'";
 }
 else {
  $command = $command . " OR dictionary = '{$dictionariesInArray[$i]}'";
 }
}

$roundedPercentValue = ((round($summedPoints / mysql_num_rows(mysql_query($command)), 3)) / 5) * 100;

$image=imagecreate(200,20);

//First color is background color
$headerBox = imagecolorallocate($image, 138, 97, 50);
$border = imagecolorallocate($image, 63, 63, 63);
$menuBox = imagecolorallocate($image, 111, 83, 51);
$black = imagecolorallocate($image, 0, 0, 0);

imagefilledrectangle($image, 0, 0, $roundedPercentValue * 2, 20, $menuBox);
imageline($image, $roundedPercentValue * 2, 0, $roundedPercentValue * 2, 20, $border);
imagestring($image,2, 95, 3, $roundedPercentValue . "%", $black);

imagepng($image);

imagedestroy($image);

mysql_close($connection);

?>